package org.myhibernate.auth;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.myhibernate.core.Template;
import org.myhibernate.core.method.PageSizeQuery;
import org.myhibernate.db.CommonLogs;

public class AuthQuery 
{
	private Template<AuthObject> template=null;
	private PageSizeQuery<AuthObject> query=null;
	private AuthObject object=null;
	public static String AUTH_USER="users";
	public static String AUTH_CREATOR="creators";
	public static String AUTH_EDITOR="editors";
	public static String AUTH_REMOVER="removers";
	public static String AUTH_MANAGER="managers";
	public static SimpleDateFormat dateFormat_YMD_HMS=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static Map<String,String> AUTH_TYPE=new HashMap<String, String>();
	static
	{ 
		AUTH_TYPE.put("AUTH_USER", "users");
		AUTH_TYPE.put("AUTH_CREATOR", "creators");
		AUTH_TYPE.put("AUTH_EDITOR", "editors");
		AUTH_TYPE.put("AUTH_REMOVER", "removers");
		AUTH_TYPE.put("AUTH_MANAGER", "managers");
	}
	public AuthQuery() {
		template=new Template<AuthObject>(AuthObject.class);
		query=(PageSizeQuery<AuthObject>) template.getPageSizeQuery();
	}
	public AuthObject create(String id,String pid)
	{
		object=new AuthObject();
		object.setId(pid);
		object.setPid(pid);
		Date date=new Date();
		object.setCreateTime(date.getTime()+"");
		object.setCreateDate(dateFormat_YMD_HMS.format(date));
		return object;
	}
	public void save()throws Exception
	{
		if (object!=null) {
			try {
				save(object);
			} catch (RuntimeException e) {
				e.printStackTrace();
				throw new RuntimeException(e.toString());
			}
		}
	}
	public void save(AuthObject object)throws Exception
	{
		if (object!=null) 
		{
			try {
				template.save(object);
			} catch (RuntimeException e) {
				e.printStackTrace();
				throw new RuntimeException(e.toString());
			}
		}
	}
	public void addToParent(AuthObject self) throws Exception 
	{
		if (template.get(self.getPid()+"")!=null)
		{
			AuthObject parentObject=template.get(self.getPid()+"");
			if (parentObject.getChildren().contains(self.getId())==false)
			{
				parentObject.getChildren().add(self.getId());
				template.update(parentObject);
			}
		}
	}
	public List<AuthObject> getChildren(AuthObject object) throws Exception
	{
		List<AuthObject> children=new ArrayList<AuthObject>();
		if (object==null) {
			return children; 
		}
		List<String> list=object.getChildren();
		for (int i = 0; i < list.size(); i++) 
		{
			AuthObject aObject=(AuthObject) template.get(list.get(i));
			if ("true".equals(aObject.getInherit()))
			{
				children.add(aObject);
			}
		}
		return children;
	}

	public List<AuthObject> getAllChildren(AuthObject object,List<AuthObject> children,String inherit) throws Exception
	{
		if (children == null) {
			children=new ArrayList<AuthObject>();
		}
		List<String> list =null;
		list=object.getChildren();
		for (int i = 0; i < list.size(); i++)
		{
			AuthObject aObject=null;
			if(template.get(list.get(i)) != null)
			{
				aObject=(AuthObject) template.get(list.get(i));
				if ("true".equals(aObject.getInherit()))
				{
					children.add(aObject);
				}
			}
			List<AuthObject> tempList=getChildren(aObject);
			if (tempList.size()>0) 
			{
				getAllChildren(aObject, children,inherit);
			}
		}
		return children;
	}
	public List<AuthObject> query(String className,String AUTH_TYPE,List<String> queryKeys) throws Exception
	{
		System.out.println("AuthQuery queryKeys="+queryKeys);
		CommonLogs.add("AuthQuery queryKeys="+queryKeys);
		List<AuthObject> list=new ArrayList<AuthObject>();
		//查询有授权用户的节点   和非继承的有权节点
		StringBuffer sql=new StringBuffer(" where ((CLASSNAME='"+className+"') and ( ");
		for (int i = 0; i < queryKeys.size(); i++) 
		{
			if (0==i)
			{
				sql.append("( "+AUTH_TYPE+" like ';"+queryKeys.get(i)+";' ) ");
			} else {
				sql.append(" or ( "+AUTH_TYPE+" like ';"+queryKeys.get(i)+";' )");
			}
		}
		sql.append(" ) ");
		
		System.out.println("AuthQuery conditions="+sql.toString());
		CommonLogs.add("AuthQuery conditions="+sql.toString());
		List<AuthObject> authList=null;
		try {
			authList = query.getListObject(0, query.query(sql.toString()));
		} catch (Exception e) {
			authList=new ArrayList<AuthObject>();
			e.printStackTrace();
		}
		
		//获取节点下面的子节点
		Map<String, Boolean> map=new HashMap<String, Boolean>();
		AuthObject tempObject=null,tempObject1=null;
		List<AuthObject> tempList=null;
		for (int i = 0; i < authList.size(); i++) 
		{
			tempObject=authList.get(i);
			if (map.get(tempObject.getId()) == null)
			{
				map.put(tempObject.getId(),true);
				list.add(tempObject);
			}
			tempList=new ArrayList<AuthObject>();
			getAllChildren(tempObject, tempList, null);
			for (int j = 0; j < tempList.size(); j++) 
			{
				tempObject1=tempList.get(j);
				if (map.get(tempObject1.getId()) == null)
				{
					map.put(tempObject1.getId(), true);
					list.add(tempObject1);
				}
			}
		}
		return list;
	}
	public Template<AuthObject> getTemplate() {
		return template;
	}
	public void close()
	{
		template.close();
	}
}
